<template>
  <div class="staff-manage">
    <el-card>
      <div class="header">
        <span>员工管理</span>
        <el-button type="primary" @click="openStaffDialog('add')">新增员工</el-button>
        <el-button @click="openGroupDialog" style="margin-left: 8px;">分组管理</el-button>
      </div>
      <el-form :inline="true" :model="filter" class="filter-bar" label-width="90px" style="margin-bottom: 16px;">
        <el-form-item label="员工姓名">
          <el-input v-model="filter.name" placeholder="员工姓名" clearable style="width: 140px;" />
        </el-form-item>
        <el-form-item label="区号">
          <el-select v-model="filter.countryCode" clearable style="width: 150px;">
            <el-option 
              v-for="item in countryCodeOptions" 
              :key="item.code" 
              :label="`${item.code} ${item.country}`" 
              :value="item.code" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="filter.mobile" placeholder="手机号" clearable style="width: 140px;" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="filter.role" multiple clearable style="width: 200px;" placeholder="选择角色">
            <el-option v-for="item in roleOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="分组">
          <el-select v-model="filter.group" clearable style="width: 140px;">
            <el-option v-for="item in groupOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <div class="filter-actions-row">
          <el-button type="primary" @click="doFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </div>
      </el-form>
      <el-table :data="tableData" style="width: 100%" :default-sort="{prop: 'id', order: 'ascending'}">
        <el-table-column prop="id" label="员工ID" width="100" />
        <el-table-column prop="name" label="员工姓名" width="120" />
        <el-table-column prop="nickname" label="昵称" width="120" />
        <el-table-column prop="mobile" label="手机号" width="200">
          <template #default="scope">
            <span>{{ scope.row.countryCode }} {{ scope.row.mobile }}</span>
            <div style="font-size: 12px; color: #666; margin-top: 2px;">
              {{ getCountryName(scope.row.countryCode) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" width="160">
          <template #default="scope">
            <el-tag v-for="role in scope.row.role" :key="role" style="margin-right: 4px; margin-bottom: 4px;">{{ role }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="group" label="分组" width="160">
          <template #default="scope">
            <el-tag v-for="g in scope.row.group" :key="g" style="margin-right: 4px;">{{ g }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最近登录时间" width="200">
          <template #default="scope">
            <span style="white-space: nowrap;">{{ scope.row.lastLoginTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginIp" label="最近登录IP" width="140" />
        <el-table-column label="绑定会员" width="120">
          <template #default="scope">
            <div v-if="scope.row.userIds && scope.row.userIds.length > 0">
              <el-tag size="small" type="info">{{ scope.row.userIds.length }}个会员</el-tag>
            </div>
            <span v-else style="color: #999; font-size: 12px;">未绑定</span>
          </template>
        </el-table-column>
        <el-table-column label="超级客服" width="100">
          <template #default="scope">
            <el-tag 
              :type="scope.row.superServicePermission ? 'success' : 'info'"
              size="small"
            >
              {{ scope.row.superServicePermission ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260">
          <template #default="scope">
            <el-button size="small" @click="editStaff(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" :disabled="scope.row.role.includes('管理员')" @click="deleteStaff(scope.row)">删除</el-button>
            <el-button size="small" @click="resetPwd(scope.row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="page.current"
        v-model:page-size="page.size"
        :total="page.total"
        layout="total, prev, pager, next, sizes"
        :page-sizes="[10, 20, 50]"
        style="margin-top: 16px; text-align: right;"
      />
    </el-card>

    <!-- 新增/编辑员工弹窗 -->
    <el-dialog v-model="staffDialog.visible" :title="staffDialog.mode === 'add' ? '新增员工' : '编辑员工'" width="500px" :close-on-click-modal="false">
      <el-form :model="staffDialog.form" :rules="staffRules" ref="staffFormRef" label-width="100px" style="margin-top: 12px;">
        <el-form-item label="员工姓名" prop="name">
          <el-input v-model="staffDialog.form.name" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="staffDialog.form.nickname" />
        </el-form-item>
        <el-form-item label="区号" prop="countryCode">
          <el-select v-model="staffDialog.form.countryCode" style="width: 150px">
            <el-option 
              v-for="item in countryCodeOptions" 
              :key="item.code" 
              :label="`${item.code} ${item.country}`" 
              :value="item.code" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="staffDialog.form.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="staffDialog.form.role" multiple clearable style="width: 100%" placeholder="请选择角色">
            <el-option v-for="item in roleOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="分组" prop="group">
          <el-select v-model="staffDialog.form.group" multiple clearable style="width: 100%">
            <el-option v-for="item in groupOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="staffDialog.form.status" style="width: 100%">
            <el-option label="启用" value="启用" />
            <el-option label="禁用" value="禁用" />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定会员">
          <div class="form-tip" style="margin-bottom: 8px; color: #666; font-size: 12px;">
            可选择绑定会员，非必填项
          </div>
          <div class="user-selector">
            <!-- 用户搜索 -->
            <el-input
              v-model="userSearchKeyword"
              placeholder="搜索会员昵称、会员ID（可选）"
              @input="searchUsers"
              style="margin-bottom: 12px; width: 300px;"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            
            <!-- 用户列表 -->
            <div class="user-list-container">
              <el-table
                :data="filteredUserList"
                @row-click="handleUserRowClick"
                style="max-height: 300px;"
                highlight-current-row
              >
                <el-table-column label="会员信息" min-width="200">
                  <template #default="scope">
                    <div class="user-info" style="display: flex; align-items: center;">
                      <el-radio 
                        :value="scope.row.id" 
                        v-model="selectedUserId"
                        style="margin-right: 8px;"
                      />
                      <el-avatar :size="32" :src="scope.row.avatar">
                        {{ scope.row.name?.charAt(0) }}
                      </el-avatar>
                      <div class="user-details" style="margin-left: 8px;">
                        <div class="user-name">{{ scope.row.name }}</div>
                        <div class="user-meta">会员ID: {{ scope.row.id }}</div>
                      </div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            
            <!-- 已选择的会员 -->
            <div class="selected-users" v-if="selectedUser">
              <h4>已选择会员 - 可选</h4>
              <div class="selected-user-tags">
                <el-tag
                  closable
                  @close="removeSelectedUser"
                  style="margin-right: 8px; margin-bottom: 8px;"
                >
                  <el-avatar :size="16" :src="selectedUser.avatar" style="margin-right: 4px;">
                    {{ selectedUser.name?.charAt(0) }}
                  </el-avatar>
                  {{ selectedUser.name }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="超级客服权限">
          <el-switch 
            v-model="staffDialog.form.superServicePermission"
            active-text="开启"
            inactive-text="关闭"
            active-color="#67c23a"
          />
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="staffDialog.form.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="staffDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitStaff">保存</el-button>
      </template>
    </el-dialog>

    <!-- 分组管理弹窗 -->
    <el-dialog v-model="groupDialog.visible" title="分组管理" width="400px" :close-on-click-modal="false">
      <el-form :model="groupDialog.form" ref="groupFormRef" label-width="80px" @submit.prevent>
        <el-form-item label="分组名称" prop="name">
          <el-input v-model="groupDialog.form.name" />
        </el-form-item>
      </el-form>
      <el-table :data="groupDialog.list" style="margin-bottom: 12px;">
        <el-table-column prop="name" label="分组名称" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" @click="editGroup(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteGroup(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="groupDialog.visible = false">关闭</el-button>
        <el-button type="primary" @click="saveGroup">保存</el-button>
        <el-button @click="addGroup">新增分组</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { Search, InfoFilled } from '@element-plus/icons-vue'

const roleOptions = ['管理员', '运营', '客服', '仓库']
const groupOptions: string[] = []
const countryCodeOptions = [
  { code: '+86', country: '中国' },
  { code: '+852', country: '中国香港' },
  { code: '+853', country: '中国澳门' },
  { code: '+886', country: '中国台湾' },
  { code: '+81', country: '日本' },
  { code: '+1', country: '美国/加拿大' },
  { code: '+44', country: '英国' },
  { code: '+49', country: '德国' },
  { code: '+33', country: '法国' },
  { code: '+61', country: '澳大利亚' },
  { code: '+82', country: '韩国' },
  { code: '+65', country: '新加坡' },
  { code: '+60', country: '马来西亚' },
  { code: '+66', country: '泰国' },
  { code: '+84', country: '越南' }
]

// 会员相关数据
interface User {
  id: string;
  name: string;
  avatar?: string;
}

// 模拟会员数据
const userList = ref<User[]>([
  {
    id: 'M001',
    name: '陈小明',
    avatar: ''
  },
  {
    id: 'M002',
    name: '刘美丽',
    avatar: ''
  },
  {
    id: 'M003',
    name: '王建国',
    avatar: ''
  },
  {
    id: 'M004',
    name: '张小红',
    avatar: ''
  },
  {
    id: 'M005',
    name: '李志强',
    avatar: ''
  },
  {
    id: 'M006',
    name: '赵雅琴',
    avatar: ''
  },
  {
    id: 'M007',
    name: '孙伟',
    avatar: ''
  },
  {
    id: 'M008',
    name: '周丽华',
    avatar: ''
  }
])

// 会员选择器相关状态
const userSearchKeyword = ref('')
const filteredUserList = ref<User[]>(userList.value)
const selectedUserId = ref('')
const selectedUser = computed(() => {
  return userList.value.find(user => user.id === selectedUserId.value)
})
const filter = reactive({ name: '', countryCode: '', mobile: '', role: [] as string[], group: '' })
const allData = ref([
  { id: 'S001', name: '张三', nickname: '小张', countryCode: '+86', mobile: '13800000001', role: ['管理员'] as string[], group: [] as string[], lastLoginTime: '2024-06-10 10:00:12', lastLoginIp: '192.168.1.10', status: '启用', remark: '', needChangePwd: false, password: '12345678', userIds: [] as string[], superServicePermission: false },
  { id: 'S002', name: '李四', nickname: '小李', countryCode: '+852', mobile: '12345678', role: ['运营', '客服'] as string[], group: [] as string[], lastLoginTime: '2024-06-11 09:30:45', lastLoginIp: '192.168.1.11', status: '启用', remark: '', needChangePwd: false, password: '12345678', userIds: [] as string[], superServicePermission: false },
  { id: 'S003', name: '王五', nickname: '小五', countryCode: '+1', mobile: '2025550182', role: ['客服'] as string[], group: [] as string[], lastLoginTime: '2024-06-12 14:20:59', lastLoginIp: '192.168.1.12', status: '禁用', remark: '', needChangePwd: false, password: '12345678', userIds: [] as string[], superServicePermission: false }
])
const page = reactive({ current: 1, size: 10, total: 0 })
const tableData = computed(() => {
  let data = allData.value
  if (filter.name) data = data.filter(row => row.name.includes(filter.name))
  if (filter.countryCode) data = data.filter(row => row.countryCode === filter.countryCode)
  if (filter.mobile) data = data.filter(row => row.mobile.includes(filter.mobile))
  if (filter.role && filter.role.length > 0) {
    data = data.filter(row => filter.role.some(role => row.role.includes(role)))
  }
  if (filter.group) data = data.filter(row => row.group.includes(filter.group))
  page.total = data.length
  const startIdx = (page.current - 1) * page.size
  return data.slice(startIdx, startIdx + page.size)
})

function doFilter() { page.current = 1 }
function resetFilter() { filter.name = ''; filter.countryCode = ''; filter.mobile = ''; filter.role = []; filter.group = ''; page.current = 1 }

const staffDialog = reactive({
  visible: false,
  mode: 'add' as 'add' | 'edit',
  form: { 
    id: '', 
    name: '', 
    nickname: '', 
    countryCode: '+86', 
    mobile: '', 
    role: [] as string[], 
    group: [], 
    status: '启用', 
    remark: '',
    userIds: [] as string[],
    superServicePermission: false
  }
})
const staffFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const staffRules = {
  name: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  countryCode: [{ required: true, message: '请选择区号', trigger: 'change' }],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^\d{5,20}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  group: [{ required: false }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],

}
function openStaffDialog(mode: 'add' | 'edit', row?: any) {
  staffDialog.mode = mode
  if (mode === 'add') {
    Object.assign(staffDialog.form, { 
      id: '', 
      name: '', 
      nickname: '', 
      countryCode: '+86', 
      mobile: '', 
      role: [] as string[], 
      group: [], 
      status: '启用', 
      remark: '',
      userIds: [],
      superServicePermission: false
    })
    // 重置会员选择器状态
    selectedUserId.value = ''
    filteredUserList.value = userList.value
    userSearchKeyword.value = ''
  } else if (row) {
    Object.assign(staffDialog.form, { 
      ...row,
      userIds: row.userIds || [],
      superServicePermission: row.superServicePermission || false
    })
    // 根据已选择的会员ID设置选中状态
    selectedUserId.value = (row.userIds && row.userIds.length > 0) ? row.userIds[0] : ''
    filteredUserList.value = userList.value
    userSearchKeyword.value = ''
  }
  staffDialog.visible = true
  nextTick(() => staffFormRef.value?.clearValidate())
}

// 会员相关函数
function searchUsers() {
  if (!userSearchKeyword.value) {
    filteredUserList.value = userList.value
    return
  }
  
  const keyword = userSearchKeyword.value.toLowerCase()
  filteredUserList.value = userList.value.filter(user => 
    user.name.toLowerCase().includes(keyword) ||
    user.id.toLowerCase().includes(keyword)
  )
}

function handleUserRowClick(row: User) {
  selectedUserId.value = row.id
  staffDialog.form.userIds = [row.id]
}

function removeSelectedUser() {
  selectedUserId.value = ''
  staffDialog.form.userIds = []
}

// 根据区号获取国家名称
function getCountryName(countryCode: string) {
  const country = countryCodeOptions.find(item => item.code === countryCode)
  return country ? country.country : countryCode
}

function editStaff(row: any) {
  openStaffDialog('edit', row)
}
function submitStaff() {
  staffFormRef.value?.validate((valid: boolean) => {
    if (!valid) return
    if (staffDialog.mode === 'add') {
      const newId = 'S' + (Math.floor(Math.random() * 9000) + 1000)
      allData.value.unshift({ 
        ...staffDialog.form, 
        id: newId, 
        lastLoginTime: '', 
        lastLoginIp: '', 
        needChangePwd: true, 
        password: '12345678',
        userIds: staffDialog.form.userIds || [],
        superServicePermission: staffDialog.form.superServicePermission || false
      })
      ElMessage.success('新增成功（mock）')
    } else {
      const idx = allData.value.findIndex(item => item.id === staffDialog.form.id)
      if (idx > -1) {
        allData.value[idx] = { 
          ...staffDialog.form, 
          lastLoginTime: allData.value[idx].lastLoginTime, 
          lastLoginIp: allData.value[idx].lastLoginIp, 
          needChangePwd: allData.value[idx].needChangePwd, 
          password: allData.value[idx].password,
          userIds: staffDialog.form.userIds || [],
          superServicePermission: staffDialog.form.superServicePermission || false
        }
        ElMessage.success('编辑成功（mock）')
      }
    }
    staffDialog.visible = false
  })
}
function deleteStaff(row: any) {
  allData.value = allData.value.filter(item => item.id !== row.id)
  ElMessage.success('删除成功')
}
function toggleStatus(row: any) {
  row.status = row.status === '禁用' ? '启用' : '禁用'
  ElMessage.success('状态已更新')
}
function resetPwd(row: any) {
  row.needChangePwd = true
  // 密码字段实际项目应加密存储，这里仅mock
  row.password = '12345678'
  ElMessage.success('密码已重置为12345678，用户首次登录需修改密码')
}

const groupDialog = reactive({
  visible: false,
  list: groupOptions.map(name => ({ name })),
  form: { name: '' },
  editIndex: -1
})
const groupFormRef = ref()
function openGroupDialog() {
  groupDialog.visible = true
  groupDialog.form.name = ''
  groupDialog.editIndex = -1
}
function addGroup() {
  if (!groupDialog.form.name) return ElMessage.warning('请输入分组名称')
  if (groupDialog.list.some(g => g.name === groupDialog.form.name)) return ElMessage.warning('分组已存在')
  groupDialog.list.push({ name: groupDialog.form.name })
  groupDialog.form.name = ''
  updateGroupOptions()
  ElMessage.success('新增成功')
}
function editGroup(row: any) {
  groupDialog.form.name = row.name
  groupDialog.editIndex = groupDialog.list.findIndex(g => g.name === row.name)
}
function saveGroup() {
  if (groupDialog.editIndex > -1) {
    if (!groupDialog.form.name) return ElMessage.warning('请输入分组名称')
    if (groupDialog.list.some((g, i) => g.name === groupDialog.form.name && i !== groupDialog.editIndex)) return ElMessage.warning('分组已存在')
    groupDialog.list[groupDialog.editIndex].name = groupDialog.form.name
    groupDialog.editIndex = -1
    groupDialog.form.name = ''
    updateGroupOptions()
    ElMessage.success('修改成功')
  }
}
function deleteGroup(row: any) {
  groupDialog.list = groupDialog.list.filter(g => g.name !== row.name)
  updateGroupOptions()
  ElMessage.success('删除成功')
}
function updateGroupOptions() {
  groupOptions.splice(0, groupOptions.length, ...groupDialog.list.map(g => g.name))
  // 清理员工分组中已被删除的分组
  allData.value.forEach(staff => {
    staff.group = staff.group.filter((g: string) => groupOptions.includes(g))
  })
}
</script>

<style scoped>
.staff-manage { padding: 32px; }
.header { display: flex; gap: 12px; align-items: center; margin-bottom: 12px; }
.filter-bar { margin-bottom: 16px; }
.filter-actions-row { margin-top: 8px; display: flex; gap: 12px; }

/* 会员选择器样式 */
.user-selector {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 16px;
  background: #fafafa;
}

.user-list-container {
  margin: 12px 0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  flex: 1;
}

.user-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.user-meta {
  font-size: 12px;
  color: #666;
}

.selected-users {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.selected-users h4 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 14px;
}

.selected-user-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}


</style> 